package com.chenxin.quartz.task.deviceOrder;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chenxin.common.core.domain.DeviceResult;
import com.chenxin.common.exception.ServiceException;
import com.chenxin.interact.domain.ToDeviceOrder;
import com.chenxin.interact.domain.UrlMap;
import com.chenxin.interact.mapper.ToDeviceOrderMapper;
import com.chenxin.interact.service.IUrlMapService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
@Component("toDeviceOrderTask")
public class ToDeviceOrderTask {
    //    创建锁，防止并发情况出现
    private Lock lock = new ReentrantLock();

    @Autowired
    private ToDeviceOrderMapper toDeviceOrderMapper;
    @Autowired
    private IUrlMapService urlMapService;

    private final RestTemplate restTemplate;

    public ToDeviceOrderTask(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder.build();
    }

    public void toDeviceOrder() {
        lock.lock();
        log.info("开始执行定时任务");
        try {
            UrlMap urlMap = urlMapService.selectUrlMapByUrlNo("PostBom");
            if (urlMap == null || urlMap.getUrlAdr().isEmpty()) {
                log.info("【PostBom】未在【wms_url_map】表中配置!");
                throw new ServiceException("【PostBom】未在【wms_url_map】表中配置!");
            }
            String url = urlMap.getUrlAdr() + urlMap.getUriAdr();

            //扫描待下发指令
            ToDeviceOrder toDeviceOrder = toDeviceOrderMapper.selectOne(new QueryWrapper<ToDeviceOrder>().lambda().eq(ToDeviceOrder::getStatus, 0).last("limit 1"));
            if (toDeviceOrder == null) {
                return;
            }

            Map<String, Object> params = new HashMap<>();
            params.put("OrderNo", toDeviceOrder.getOrderNo());
            params.put("Type", toDeviceOrder.getType());
            params.put("Priority", toDeviceOrder.getPriority());

            List<Map<String, Object>> dataList = new ArrayList<>();
            //查询出当前工单下的所有待下发明细
            QueryWrapper<ToDeviceOrder> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(ToDeviceOrder::getStatus, 0)
                    .eq(ToDeviceOrder::getOrderNo, toDeviceOrder.getOrderNo());
            List<ToDeviceOrder> toDeviceOrders = toDeviceOrderMapper.selectList(queryWrapper);
            for (ToDeviceOrder toDeviceOrder1 : toDeviceOrders) {
                Map<String, Object> data = new HashMap<>();
                data.put("Priority", toDeviceOrder1.getPriority());
                data.put("SN", toDeviceOrder1.getSN());
                data.put("TowerNo", toDeviceOrder1.getTowerNo());
                dataList.add(data);
            }
            params.put("Data", dataList);
            //下发
            DeviceResult respond = restTemplate.postForObject(url, params, DeviceResult.class);
            if (respond == null) {
                throw new ServiceException("【PostBom】请求失败!");
            }
            if (respond.getSuccess()) {
                log.info("【PostBom】成功!");
            } else {
                log.info("【PostBom】失败!");
            }
        } catch (Exception e) {
            log.error("【PostBom】请求异常:{}", e.getMessage());
        } finally {
            lock.unlock();
        }
    }
}
